import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios';
import sp from '../native/sp.ts';
import {SP_COOKIE} from '../utils/Contants.ts';
import {ToastAndroid} from 'react-native';

const service = axios.create({
  baseURL: 'https://www.wanandroid.com/',
  timeout: 5000,
  maxRate: 0,
});

const headers = {
  'Content-Type': 'application/x-www-form-urlencoded',
};

service.interceptors.request.use(config => {
  sp.getStringSet(SP_COOKIE, (cookies: string[]) => {
    config.headers['cookie'] = cookies;
  });
  return config;
});

service.interceptors.response.use(
  response => {
    const cookies = response.headers['set-cookie'];
    if (cookies != null && cookies.length > 0) {
      const cookieSet = cookies[0].split(';');
      sp.setStringSet(SP_COOKIE, cookieSet);
    }
    if (response.data.errorCode === 0) {
      return response.data.data;
    } else {
      ToastAndroid.show('服务器错误', ToastAndroid.SHORT);
      return Promise.reject(Error('服务器错误'));
    }
  },
  error => {
    // let status = 405
    // switch (status) {
    //   case 400:
    //     error.message = '请求错误';
    //     break;
    //   case 401:
    //     // Token 过期时
    //     // logout()
    //     break;
    //   case 403:
    //     error.message = '拒绝访问';
    //     break;
    //   case 404:
    //     error.message = '请求地址出错';
    //     break;
    //   case 405:
    //     console.log(405);
    //     error.message = '请求方法错误';
    //     break;
    //   case 408:
    //     error.message = '请求超时';
    //     break;
    //   case 500:
    //     error.message = '服务器内部错误';
    //     break;
    //   case 501:
    //     error.message = '服务未实现';
    //     break;
    //   case 502:
    //     error.message = '网关错误';
    //     break;
    //   case 503:
    //     error.message = '服务不可用';
    //     break;
    //   case 504:
    //     error.message = '网关超时';
    //     break;
    //   case 505:
    //     error.message = 'HTTP 版本不受支持';
    //     break;
    //   default:
    //     break;
    // }
    // console.log(error.message);
    ToastAndroid.show('网络错误', ToastAndroid.SHORT);
    return Promise.reject(error);
  },
);

export function postRequest<T>(url: string, params: any): Promise<T> {
  return service.post<T>(url, params, {
    headers: headers,
  });
}

export function getRequest<T>(url: string, params?: any): Promise<T> {
  return service.get<T>(url, {
    headers: headers,
    params: params,
  });
}

// export function get<T>(url: string, params: any): Promise<BaseResponse<T>> {
//   return service.get<T>(url, {
//     headers: headers,
//     params: params,
//   });
// }

export default service;
